﻿using System;

namespace Microsoft.Services.Clab.UI.Mvvmc
{
    public class ViewModelProperty
    {
        public ViewModelProperty(string name, bool notifyPropertyChanged = true, Action notifyPropertyChangedCallback = null, bool isSerialized = true)
        {
            this.Name = name;
            this.NotifyPropertyChanged = notifyPropertyChanged;
            this.NotifyPropertyChangedCallback = notifyPropertyChangedCallback;
            this.IsSerialized = isSerialized;
        }

        internal ViewModelBase ParentViewModel { get; set; }

        public string Name { get; set; }
        public bool NotifyPropertyChanged { get; set; }
        public Action NotifyPropertyChangedCallback { get; set; }
        public bool IsSerialized { get; set; }

        public T GetValue<T>()
        {
            if (currentValue != null)
            {
                return (T)currentValue;
            }
            else
            {
                return default(T);
            }
        }

        public void SetValue<T>(T value)
        {
            var isChanged = false;

            if (value == null)
            {
                isChanged = currentValue != null;
            }
            else
            {
                isChanged = !value.Equals(currentValue);
            }

            currentValue = value;
            if (isChanged && this.NotifyPropertyChanged)
            {
                if (this.NotifyPropertyChangedCallback != null)
                {
                    this.NotifyPropertyChangedCallback();
                }
                this.ParentViewModel.OnPropertyChangedInternal(this.Name);
            }
        }

        private object currentValue;
    }
}
